package com.ruubypay.biz.utils.io.resource;

import org.apache.commons.io.IOUtils;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * 资源文件处理类
 * @author chenhaiyang
 */
public class ResourceConverter {

    /**
     * 将输入流转换成字符串
     * @param in 输入流
     * @return 返回字符串
     */
    public static String converterInputStreamAsString(InputStream in) throws IOException {


        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(in,"utf-8");
            BufferedReader bufferedReader = new BufferedReader(isr);
            StringBuilder str = new StringBuilder();
            String lineTxt;
            while ((lineTxt = bufferedReader.readLine()) != null) {
                str.append(lineTxt);
                str.append("\n");
            }
            return str.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(in!=null){
                in.close();
            }
            if(isr!=null){
                isr.close();
            }
        }
        return "";
    }

    /**
     * 将输入流转换成base64类型的图片
     * @param in 资源流
     * @return 返回base64g格式的图片
     */
    public static String converterstreamAsBase64Str(InputStream in) throws IOException {
        try {
            byte[] data = IOUtils.toByteArray(in);
            // 对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            // 返回Base64编码过的字节数组字符串
            return encoder.encode(data);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(in!=null){
                in.close();
            }
        }
        return "";
    }
}
